﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Common;
using StoragePeriod.Data;
using StoragePeriod.Web.Common;
using System.Text;
using StoragePeriod.Model.RawDict;
using StoragePeriod.BLL.RawDict;

namespace StoragePeriod.Web.StorageForecast
{
    public partial class StorageForecast : SecurityPage
    {
        T_RawMaterial tRawMaterial = new T_RawMaterial();//原料操作

        #region 继承
        public override string PrivCode()
        {
            return "fd31e9e19a15dc48";
        }
        #endregion

        private void DropBandingSearch()
        {
            List<OperationTeam> OperationList = OperationTeam.Where("ParentId=@0", 0).OrderByDescending(p => p.id).ToList();
            this.Drop_OperationSearch.DataSource = OperationList;
            this.Drop_OperationSearch.DataValueField = "id";
            this.Drop_OperationSearch.DataTextField = "OTName";
            this.Drop_OperationSearch.DataBind();
            this.Drop_OperationSearch_SelectedIndexChanged(null, null);

            List<RawMaterialType> TargetsList = RawMaterialType.Where("ParentId=@0 and TypeInfoid=@1", 0,Convert.ToInt32(EnumData.TypeInfo.预测指标)).OrderByDescending(p => p.id).ToList();
            this.Drop_Targets.DataSource = TargetsList;
            this.Drop_Targets.DataValueField = "id";
            this.Drop_Targets.DataTextField = "TypeName";
            this.Drop_Targets.DataBind();
            this.Drop_Targets_SelectedIndexChanged(null, null);
        }

        private void LoadDrop()
        { 
            this.Drop_TemperatureType.Items.Clear();
            foreach (int i in Enum.GetValues(typeof(EnumData.TemperatureType)))
            {
                ListItem item = new ListItem();
                item.Value = i.ToString();
                item.Text = Enum.GetName(typeof(EnumData.TemperatureType), i).Replace("_","")+"℃";
                this.Drop_TemperatureType.Items.Add(item);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            this.LoadDrop();
            BindTreeView();
            DropBandingSearch();
            LeftLable.Text = "贮存期预测";

            SYS_Users md = SYS_Users.Where("UserCode=@0", User.Identity.Name).First();
            OperationTeam team = OperationTeam.Where("id=@0", Convert.ToInt32(md.UserType)).First();
            this.Drop_OperationSearch.SelectedValue = team.ParentId.ToString();
            this.Drop_OperationSearch_SelectedIndexChanged(null, null);
            this.Drop_TeamSearch.SelectedValue = team.id.ToString();
            if (md.RoleName != "管理员")
            {
                this.Drop_OperationSearch.Enabled = false;
                this.Drop_TeamSearch.Enabled = false;
            }

            this.RepImgListBind();

            this.LoadPriv();
        }

        /// <summary>
        /// 加载权限控件
        /// </summary>
        private void LoadPriv()
        {
            this.Btn_AddImg.Visible = IsExisPriv("dd10b3c59866e745");
            this.Btn_DelImg.Visible = IsExisPriv("722fae95320532ab");
        }

        public void BindTreeView()
        {
            NutrientsTree.Nodes.Clear();
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0 and Typeinfoid=@1", 0, Convert.ToInt32(EnumData.TypeInfo.食品检测)).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.EToString(),
                    Target = "Parent",
                };
                childNode = GetRawByTypeId(childNode);
                NutrientsTree.Nodes.Add(childNode);
            });
            SysTree_SelectedNodeChanged(null, null);
        }

        private TreeNode GetRawByTypeId(TreeNode tn)
        {
            int Pid = int.Parse(tn.Value);
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0", Pid).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.ToString(),
                    Target = "Parent"
                };
                childNode = GetRawByTypeId(childNode);
                tn.ChildNodes.Add(childNode);
            });

            int TypeId = int.Parse(tn.Value);
            List<E_RawMaterial> rmlist = rmlist = tRawMaterial.GetModelList("PeriodTypeStorageID =" + TypeId);

            rmlist.ForEach(a =>
            {
                TreeNode rnod = new TreeNode()
                {
                    Text = a.RAWName,
                    Value = a.id.EToString(),
                    Target = "Child"
                };
                tn.ChildNodes.Add(rnod);
            });
            return tn;
        }

        protected void SysTree_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn != null && tn.Target == "Child")
            {
                SetContent();
            }
        }

        protected void btn_Del_Click(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            int id = 0;
            Int32.TryParse(tn.Value, out id);
            if (tn.Target == "Child")
            {
                IntroduceStorage.Delete("id == @0", id);
                string script = "<script type='text/javascript'>alert('删除成功！');</script>";
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "", script, false);
                BindTreeView();
            }
            else
            {
                string script = "<script type='text/javascript'>alert('您不能删除分类！');</script>";
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "", script, false);
            }
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Txt_Search.Text))
            {
                return;
            }
            for (int i = 0; i < NutrientsTree.Nodes.Count; i++)
            {
                for (int ii = 0; ii < NutrientsTree.Nodes[i].ChildNodes.Count; ii++)
                {
                    if (NutrientsTree.Nodes[i].ChildNodes[ii].Text.Contains(Txt_Search.Text))
                    {
                        TreeNode node = NutrientsTree.Nodes[i].ChildNodes[ii];
                        string text = node.Text;
                        node.Text = HttpUtility.HtmlDecode(node.Text).Replace(Txt_Search.Text, "<span class='Red'>" + Txt_Search.Text + "</span>");
                    }
                }
            }
        }

        protected void Drop_OperationSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.Drop_OperationSearch.SelectedItem != null)
            {
                int ParentId = Convert.ToInt32(this.Drop_OperationSearch.SelectedValue);
                List<OperationTeam> TeamList;
                if (ParentId == -1)
                {
                    TeamList = new List<OperationTeam>();
                }
                else
                {
                    TeamList = OperationTeam.Where("ParentId=@0", ParentId).ToList();
                }
                this.Drop_TeamSearch.DataSource = TeamList;
                this.Drop_TeamSearch.DataValueField = "id";
                this.Drop_TeamSearch.DataTextField = "OTName";
                this.Drop_TeamSearch.DataBind();
            }
        }

        protected void Drop_Targets_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.Drop_Targets.SelectedItem != null)
            {
                int ParentId = Convert.ToInt32(this.Drop_Targets.SelectedValue);
                List<RawMaterialType> list = RawMaterialType.Where("ParentId=@0",ParentId).ToList();
                this.Drop_TargetsInfo.DataSource = list;
                this.Drop_TargetsInfo.DataValueField = "id";
                this.Drop_TargetsInfo.DataTextField = "TypeName";
                this.Drop_TargetsInfo.DataBind();
            }
        }

        protected void SetContent()
        {
            #region 初始化

            this.lbl_SelRawName.Text = "";//已选原料
            this.TxT_FactValue.Text = "";//实际值
            this.IntroContent.InnerHtml = "";//贮存知识

            #endregion

            string operation = this.Drop_OperationSearch.SelectedValue;
            string team = this.Drop_TeamSearch.SelectedValue;
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn == null || tn.Target == "Parent") return;

            this.lbl_SelRawName.Text = "已选原料：" + tn.Text;

            #region 设置贮存知识
            
            List<IntroduceStorage> introlist = IntroduceStorage.Where("TypeID == @0", Convert.ToInt32(tn.Value)).ToList();
            if (introlist.Count > 0) this.IntroContent.InnerHtml = introlist.First().ContentText;

            #endregion

            #region 实际值设置

            //List<ScoreData> scoredatalist = ScoreData.Where("RawId=@0", int.Parse(tn.Value)).ToList();
            //if (scoredatalist.Count > 0)
            //{
            //    scoredatalist = scoredatalist.GroupBy(s => s.ScoreTime).ToList().OrderByDescending(p => p.Key).FirstOrDefault().ToList();
            //    if (scoredatalist.Count > 0)
            //    {
            //        this.TxT_FactValue.Text = scoredatalist.Sum(f => f.Score).ToString();
            //    }
            //}


            #endregion
        }

        protected void Btn_ParameterSet_Click(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn == null || tn.Target == "Parent")
            {
                UtilityUI.Alert(this.UpdatePanel1, "请选择原料");
                return;
            }
            int RawId = Convert.ToInt32(tn.Value);

            StringBuilder sb = new StringBuilder();
            CalculateModel md = CalculateModel.Where("RawId=@0 and CalculateType=@1", RawId, Convert.ToInt32(EnumData.CalculateType.温度时间互推计算)).FirstOrDefault();
            if (md == null)
            {
                sb.Append("'',");
                sb.Append("'',");
            }
            else
            {
                sb.Append("'" + md.P_SumCount + "',");
                sb.Append("'"+md.P_X+"',");
            }

            for (int Temperature = 1; Temperature <= 4; Temperature++)
            {
                CalculateModel md_K = CalculateModel.Where("RawId=@0 and TemperatureType=@1 and CalculateType=@2", RawId, Temperature, Convert.ToInt32(EnumData.CalculateType.主观评分计算)).FirstOrDefault();
                sb.Append(md_K == null ? "''," : "'"+md_K.P_K+"',");

            }
            UtilityUI.Load(this.UpdatePanel1, "SetTxt(" + sb.ToString().TrimEnd(',') + ");Showdlg();");
        }

        protected void btPost_Click(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            int RawId = Convert.ToInt32(tn.Value);
            CalculateModel md = CalculateModel.Where("RawId=@0 and CalculateType=@1",RawId,Convert.ToInt32(EnumData.CalculateType.温度时间互推计算)).FirstOrDefault();
            bool IsAdd=(md==null);
            if (this.txt_P_SumCount.Text.Trim() != "" && this.txt_P_X.Text.Trim() != "")
            {
                if (md == null)
                    md = new CalculateModel();

                md.Rawid=RawId;
                md.P_SumCount = Convert.ToDouble(this.txt_P_SumCount.Text.Trim());
                md.P_X = Convert.ToDouble(this.txt_P_X.Text.Trim());
                md.CalculateType = Convert.ToInt32(EnumData.CalculateType.温度时间互推计算);
                md.Addtime = DateTime.Now;

                if (IsAdd)
                    CalculateModel.Insert(md);
                else
                    CalculateModel.Update(md, "id=@0", md.id);
            }

            foreach (int Temperature in Enum.GetValues(typeof(EnumData.TemperatureType)))
            {
                CalculateModel md_K = CalculateModel.Where("RawId=@0 and TemperatureType=@1 and CalculateType=@2", RawId, Temperature, Convert.ToInt32(EnumData.CalculateType.主观评分计算)).FirstOrDefault();
                bool IsAdd_K = (md_K == null);

                string strP_K = "";
                switch (Enum.GetName(typeof(EnumData.TemperatureType),Temperature))
                { 
                    case "_5":
                        strP_K = this.txt_P_K_1.Text.Trim();
                        break;
                    case "_15":
                        strP_K = this.txt_P_K_2.Text.Trim();
                        break;
                    case "_25":
                        strP_K = this.txt_P_K_3.Text.Trim();
                        break;
                    case "_35":
                        strP_K = this.txt_P_K_4.Text.Trim();
                        break;
                }

                if (strP_K != "")
                {
                    if (md_K == null)
                        md_K = new CalculateModel();

                    md_K.Rawid = RawId;
                    md_K.TemperatureType = Temperature;
                    md_K.P_K = Convert.ToDouble(strP_K);
                    md_K.CalculateType = Convert.ToInt32(EnumData.CalculateType.主观评分计算);
                    md_K.Addtime = DateTime.Now;

                    if (IsAdd_K)
                        CalculateModel.Insert(md_K);
                    else
                        CalculateModel.Update(md_K, "id=@0", md_K.id);
                }
            }
            UtilityUI.Alert(this.UpdatePanel1, "保存成功！");
        }

        //保存图片
        protected void btn_SaveImg_Click(object sender, EventArgs e)
        {
            string strFileName=this.file_ImgPath.FileName;
            string[] strS=strFileName.Split('.');
            string strName=Guid.NewGuid()+"."+strS[strS.Length-1];
            this.file_ImgPath.SaveAs(MapPath("~/UpLoad/") + strName);

            ImgView img = new ImgView();
            img.Imgname = this.txt_addImgName.Text.Trim();
            img.ImgPath = strName;
            img.UpLoadTime = DateTime.Now;
            img.UpLoadUserID = CurrentUser.id;
            img.UpLoadUserName = CurrentUser.UserName;
            img.Description = this.txt_addImgDescription.Text.Trim();
            ImgView.Insert(img);

            this.HidPageIndex.Value = "1";
            this.RepImgListBind();
        }

        //删除图片
        protected void Btn_DelImg_Click(object sender, EventArgs e)
        {
            int ImgID = Convert.ToInt32(this.HidImgID.Value);
            if (ImgID != 0)
            {
                ImgView.Delete("id=@0", ImgID);
            }
            this.HidPageIndex.Value = "1";
            this.HidIsNext.Value = "1";
            this.RepImgListBind();
        }

        //绑定图片列表
        private void RepImgListBind()
        {
            int pageindex = Convert.ToInt32(this.HidPageIndex.Value);
            int pagesize = 5;
            int rowcount = ImgView.All().Count();
            this.HidPageCount.Value = ((rowcount % pagesize > 0) ? rowcount / pagesize + 1 : rowcount / pagesize).ToString();

            this.RepImgList.DataSource = ImgView.All().OrderByDescending(p => p.UpLoadTime).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
            this.RepImgList.DataBind();

            //加载默认指定JS
            UtilityUI.Load(this.UpdatePanel1, "SetShowPage();");
        }

        //上一页
        protected void Btn_List_Prve_Click(object sender, EventArgs e)
        {
            int pageindex = Convert.ToInt32(this.HidPageIndex.Value);
            int pagecount = Convert.ToInt32(this.HidPageCount.Value);

            if (pageindex > 1)
            {
                this.HidPageIndex.Value = (pageindex - 1).ToString();
                this.RepImgListBind();
            }
        }

        //下一页
        protected void Btn_List_Next_Click(object sender, EventArgs e)
        {
            int pageindex = Convert.ToInt32(this.HidPageIndex.Value);
            int pagecount = Convert.ToInt32(this.HidPageCount.Value);

            if (pageindex < pagecount)
            {
                this.HidPageIndex.Value = (pageindex + 1).ToString();
                this.RepImgListBind();
            }
        }

        protected void Btn_Calulate_Click(object sender, EventArgs e)
        { 
            //通过选择的指标进行相应的计算

            //主观评分计算
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn == null || tn.Target == "Parent")
            {
                UtilityUI.Alert(this.UpdatePanel1, "请选择原料");
                return;
            }

            int RawId = Convert.ToInt32(tn.Value);
            int TemperatureId = Convert.ToInt32(this.Drop_TemperatureType.SelectedValue);
            CalculateModel md_K = CalculateModel.Where("RawId=@0 and TemperatureType=@1 and CalculateType=@2", RawId, TemperatureId, Convert.ToInt32(EnumData.CalculateType.主观评分计算)).FirstOrDefault();
            if (md_K == null)
            {
                UtilityUI.Alert(this.UpdatePanel1, "没有对应温度下的计算公式！");
                return;
            }

            if (this.txt_licunTime.Text.Trim() == "")
            {
                UtilityUI.Alert(this.UpdatePanel1, "请输入历存时间！");
                return;
            }

            double K = Convert.ToDouble(md_K.P_K);
            double Time = 0;
            if (this.Drop_danwei.SelectedValue == "0")
            {
                Time = Convert.ToDouble(this.txt_licunTime.Text.Trim());
            }
            else
            {
                Time = Convert.ToDouble(this.txt_licunTime.Text.Trim()) / 24;
            }

            double y = K * Time + 10;

            this.txt_centent.Text = this.GetStrByY(Convert.ToInt32(y));

            //包含主观评分计算、客观评分计算  客观指标 计算公式需要考虑公式的变动性
        }

        private string GetStrByY(int y)
        {
            string str = "叶菜品质损失严重，不能用于食用！";
            switch (y)
            { 
                case 10:
                    str = "叶菜品质完好，新鲜、完整";
                    break;
                case 9:
                    str = "叶菜品质有很微小的降低，整体色泽较好、五异味、无萎蔫";
                    break;
                case 8:
                    str = "叶菜品质有一定程度的降低，有萎蔫的迹象";
                    break;
                case 7:
                    str = "叶菜品质明显降低，色泽变化、有萎蔫";
                    break;
                case 6:
                    str = "叶菜品质有较大程度的降低，但勉强能够食用，异味不明显";
                    break;
            }
            return str;
        }

        protected void Btn_TimeYC_Click(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn == null || tn.Target == "Parent")
            {
                UtilityUI.Alert(this.UpdatePanel1, "请选择原料");
                return;
            }
            int RawId = Convert.ToInt32(tn.Value);
            CalculateModel md = CalculateModel.Where("RawId=@0 and CalculateType=@1", RawId, Convert.ToInt32(EnumData.CalculateType.温度时间互推计算)).FirstOrDefault();
            if (md == null)
            {
                UtilityUI.Alert(this.UpdatePanel1, "没有对应计算公式！");
                return;
            }

            if (this.txt_Temperature.Text.Trim() == "")
            {
                UtilityUI.Alert(this.UpdatePanel1, "请输入温度！");
                return;
            }

            double wendu = Convert.ToDouble(this.txt_Temperature.Text.Trim());
            double y = Convert.ToDouble(md.P_SumCount) - Convert.ToDouble(md.P_X) * wendu;

            if (this.Drop_TiemYC.SelectedValue == "0")//天
            {
                this.txt_TimeResult.Text = Math.Round(Convert.ToDecimal(y), 2).ToString();
            }
            else//小时
            {
                this.txt_TimeResult.Text = Math.Round(Convert.ToDecimal(y)*24, 2).ToString();
            }
        }

        protected void Btn_TemperatureYC_Click(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn == null || tn.Target == "Parent")
            {
                UtilityUI.Alert(this.UpdatePanel1, "请选择原料");
                return;
            }
            int RawId = Convert.ToInt32(tn.Value);
            CalculateModel md = CalculateModel.Where("RawId=@0 and CalculateType=@1", RawId, Convert.ToInt32(EnumData.CalculateType.温度时间互推计算)).FirstOrDefault();
            if (md == null)
            {
                UtilityUI.Alert(this.UpdatePanel1, "没有对应计算公式！");
                return;
            }

            if (this.txt_Time.Text.Trim() == "")
            {
                UtilityUI.Alert(this.UpdatePanel1, "请输入时间(单位：天)！");
                return;
            }

            double tian = Convert.ToDouble(this.txt_Time.Text.Trim());
            double X = (Convert.ToDouble(md.P_SumCount) - tian) / Convert.ToDouble(md.P_X);
            this.txt_TemperatureResult.Text = Math.Round(Convert.ToDecimal(X), 2).ToString();
            UtilityUI.Load(this.UpdatePanel1, "ShowNav(1);");
        }
    }
}